package com.ithema.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ithema.reggie.common.Page;
import com.ithema.reggie.common.R;
import com.ithema.reggie.entity.Category;
import com.ithema.reggie.entity.Setmeal;
import com.ithema.reggie.entity.SetmealDish;
import com.ithema.reggie.dto.SetmealDto;
import com.ithema.reggie.exception.BusinessException;
import com.ithema.reggie.mapper.CategoryMapper;
import com.ithema.reggie.mapper.SetMealMapper;
import com.ithema.reggie.mapper.SetmealDishMapper;
import com.ithema.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetMealMapper setMealMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    @Autowired
    CategoryMapper categoryMapper;
    //新增方法实现
    @Override
    public R save(SetmealDto setmealDto) {

        //1.保存setmeal
        //1.1 设置俩时间
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(setmealDto.getCreateTime());

        //1.2 调用mapper保存套餐基本信息,别忘记返回主键
        setMealMapper.save(setmealDto);

        //2.批量保存套餐中的菜品
        //2.1 获取套餐中的菜品集合
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        //2.2 遍历集合,获取每个菜品,给菜品设置套餐id,排序,俩用户,俩时间
        if (CollUtil.isNotEmpty(setmealDishes)) {
            setmealDishes.forEach(sd -> {
                //给菜品设置套餐id,排序,俩用户,俩时间
                sd.setSetmealId(setmealDto.getId());
                sd.setSort(0);

                sd.setCreateUser(setmealDto.getCreateUser());
                sd.setUpdateUser(setmealDto.getUpdateUser());

                sd.setCreateTime(setmealDto.getCreateTime());
                sd.setUpdateTime(setmealDto.getUpdateTime());
            });

            //2.3 批量保存套餐中的菜品
            setmealDishMapper.batchSave(setmealDishes);
        }




        return R.success(null);
    }

    /**
     * 作用：展示套餐列表
     * @param pageNum  当前页
     * @param pageSize  页面大小
     * @param name  菜品的名称
     * @return
     */
    @Override
    public R findByPage(Integer pageNum, Integer pageSize, String name) {

        //1.先查询套餐分类信息 list
        List<Category> categoryList = categoryMapper.findAllByType(2);

        //2.把list转成map (key:分类id,value:分类名称)
        Map<Long,String> categoryMap = new HashMap<>();
        categoryList.forEach(c -> {
            categoryMap.put(c.getId(),c.getName());
        });

        //3.设置分页参数
        PageHelper.startPage(pageNum,pageSize);

        //4.查询所有(name)
        List<Setmeal> list = setMealMapper.finfAll(name);

        //5.封装PageInfo
        PageInfo<Setmeal> pageInfo = new PageInfo<>(list);

        //6.新建一个套餐dto集合
        List<SetmealDto> dtoList = new ArrayList<>();

        //7.遍历套餐集合,获取每个套餐,将套餐封装套餐dto对象,且给每个dto设置分类名称,将dto放入dto集合中
        if (CollUtil.isNotEmpty(list)) {

            list.forEach(s -> {
                //将套餐封装套餐dto对象,且给每个dto设置分类名称,将dto放入dto集合中
                SetmealDto dto = new SetmealDto();
                BeanUtils.copyProperties(s,dto);

                dto.setCategoryName(categoryMap.get(s.getCategoryId()));

                dtoList.add(dto);
            });
        }


        //8.返回page
        return R.success(new Page<>(dtoList,pageInfo.getTotal()));
    }


    /**
     * 作用：批量删除
     * @param ids  要删除套餐的id
     * @return
     */
    @Override
    public R batchDelete(Long[] ids) {
        //1.判断是否选中套餐，如果没有选中套餐，则提示
        if (ArrayUtil.isEmpty(ids)) {
            throw new BusinessException("请选择你要删除的套餐~");
        }

        //2.判断是否有起售的套餐，如果有则不能删除
        List<Setmeal> list = setMealMapper.findOnsaleByIds(ids);
        if (CollUtil.isNotEmpty(list)) {
            throw new BusinessException("请先停售套餐在删除~~");
        }

        //3.若都停售，删除setmeal中的数据
        setMealMapper.batchDelectBySetmealIds(ids);

        //4.删除setmeal_dish中的数据
        setmealDishMapper.batchDeleteSetmealDish(ids);

        //5.返回
        return R.success(null);
    }

    @Override
    public R findById(Long id) {
        //1.查询套餐基本信息
        Setmeal setmeal = setMealMapper.findById(id);

        //2.查询套餐菜品种类信息
        List<SetmealDish> smdList = setmealDishMapper.findDishById(id);

        //3.将两个信息封装dto对象返回
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        setmealDto.setSetmealDishes(smdList);

        return R.success(setmealDto);
    }

    //更新套餐带上菜品
    @Override
    public R update(SetmealDto setmealDto) {

        //1.更新setmeal修改时间，更新setmeal
        setmealDto.setUpdateTime(LocalDateTime.now());
        setMealMapper.update(setmealDto);

        //2.根据setmealid先删除菜品表中的所有数据
        setmealDishMapper.deleteBySetmealId(setmealDto.getId());

        //3.获取页面传递过来的数据，批量保存
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        if (CollUtil.isNotEmpty(dishes)) {
            for (SetmealDish dish : dishes) {
                dish.setSetmealId(setmealDto.getId());
                dish.setSort(1);

                dish.setUpdateTime(setmealDto.getUpdateTime());
                dish.setCreateTime(setmealDto.getCreateTime());

                dish.setUpdateUser(setmealDto.getUpdateUser());
                dish.setCreateUser(setmealDto.getCreateUser());
            }
            //3.2保存所有菜品对象
            setmealDishMapper.batchSave(dishes);
        }
        return R.success(null);
    }

    /**
     * 根据套餐的类别展示套餐
     * @param categoryId
     * @param status
     * @return
     */
    @Override
    public R findOnSaleByCategoruId(Long categoryId, Integer status) {

        List<Setmeal> setmealList = setMealMapper.findByCategoryIdAndStatus(categoryId,status);
        return R.success(setmealList);
    }

}
